#include "patient_client.h"
#include <QVBoxLayout>
#include <QTabWidget>
#include <QInputDialog>
#include <QMessageBox>
#include <QSqlQuery>
#include <QLabel>
#include <QSqlError>
#include <QPushButton>
#include <QDate>
#include <QDebug>

PatientClient::PatientClient(const QString &name, QWidget *parent)
    : QWidget(parent), patientName(name)
{
    setWindowTitle("Patient Client");
    resize(600, 400);
    setupUI();
}

void PatientClient::setupUI()
{
    QTabWidget *tabWidget = new QTabWidget(this);

    // --- 查看病历界面 ---
    QWidget *viewRecordTab = new QWidget();
    QVBoxLayout *viewRecordLayout = new QVBoxLayout(viewRecordTab);
    QLabel *recordLabel = new QLabel(viewRecordTab);
    viewRecordLayout->addWidget(recordLabel);
    viewRecordTab->setLayout(viewRecordLayout);

    int patientId = getPatientId(patientName); // 获取患者ID

    // 从 medical_history 表中获取病历记录
    QSqlQuery query;
    query.prepare("SELECT d.name, mh.diagnosis, mh.treatment, mh.visit_date "
                  "FROM medical_history mh "
                  "JOIN doctors d ON mh.doctor_id = d.doctor_id "
                  "WHERE mh.patient_id = ?");
    query.addBindValue(patientId);

    QString recordText;
    if (query.exec()) {
        while (query.next()) {
            QString doctorName = query.value(0).toString();
            QString diagnosis = query.value(1).toString();
            QString treatment = query.value(2).toString();
            QString visitDate = query.value(3).toString();
            recordText.append(QString("医生: %1\n诊断: %2\n治疗: %3\n就诊日期: %4\n\n")
                              .arg(doctorName, diagnosis, treatment, visitDate));
        }
    } else {
        recordText = "查询病历失败：" + query.lastError().text();
    }

    if (recordText.isEmpty()) {
        recordLabel->setText("暂无病历");
    } else {
        recordLabel->setText(recordText);
    }

    tabWidget->addTab(viewRecordTab, "查看病历");

    // --- 提交病历界面 ---
    QWidget *submitRecordTab = new QWidget();
    QVBoxLayout *submitRecordLayout = new QVBoxLayout(submitRecordTab);
    QPushButton *submitRecordButton = new QPushButton("提交病历", submitRecordTab);
    submitRecordLayout->addWidget(submitRecordButton);
    submitRecordTab->setLayout(submitRecordLayout);

    connect(submitRecordButton, &QPushButton::clicked, [&]() {
        bool ok;
        QString newDiagnosis = QInputDialog::getText(this, "提交病历", "请输入诊断:", QLineEdit::Normal, "", &ok);
        QString newTreatment = QInputDialog::getText(this, "提交病历", "请输入治疗:", QLineEdit::Normal, "", &ok);
        if (ok && !newDiagnosis.isEmpty() && !newTreatment.isEmpty()) {
            QSqlQuery insertQuery;
            insertQuery.prepare("INSERT INTO medical_history (patient_id, doctor_id, diagnosis, treatment, visit_date) VALUES (?, ?, ?, ?, ?)");
            insertQuery.addBindValue(patientId); // 使用绑定变量
            insertQuery.addBindValue(getCurrentDoctorId()); // 获取当前医生ID
            insertQuery.addBindValue(newDiagnosis);
            insertQuery.addBindValue(newTreatment);
            insertQuery.addBindValue(QDate::currentDate()); // 使用当前日期
            if (insertQuery.exec()) {
                QMessageBox::information(this, "成功", "病历提交成功！");
            } else {
                QMessageBox::warning(this, "错误", "病历提交失败：" + insertQuery.lastError().text());
            }
        }
    });

    tabWidget->addTab(submitRecordTab, "提交病历");

    // --- 预约医生界面 ---
    QWidget *appointmentTab = new QWidget();
    QVBoxLayout *appointmentLayout = new QVBoxLayout(appointmentTab);

    QLabel *doctorLabel = new QLabel("选择医生:", appointmentTab);
    doctorComboBox = new QComboBox(appointmentTab);

    // 从数据库获取医生列表
    QSqlQuery doctorQuery("SELECT doctor_id, name FROM doctors");
    while (doctorQuery.next()) {
        int doctorId = doctorQuery.value(0).toInt();
        QString doctorName = doctorQuery.value(1).toString();
        doctorComboBox->addItem(doctorName, doctorId);
    }

    QLabel *appointmentLabel = new QLabel("预约时间:", appointmentTab);
    appointmentDateTimeEdit = new QDateTimeEdit(QDateTime::currentDateTime(), appointmentTab);
    appointmentDateTimeEdit->setCalendarPopup(true);

    QPushButton *requestAppointmentButton = new QPushButton("提交预约请求", appointmentTab);

    appointmentLayout->addWidget(doctorLabel);
    appointmentLayout->addWidget(doctorComboBox);
    appointmentLayout->addWidget(appointmentLabel);
    appointmentLayout->addWidget(appointmentDateTimeEdit);
    appointmentLayout->addWidget(requestAppointmentButton);

    connect(requestAppointmentButton, &QPushButton::clicked, [&]() {
        onRequestAppointment();
    });

    tabWidget->addTab(appointmentTab, "预约医生");

    // --- 查看预约状态界面 ---
    QWidget *viewAppointmentTab = new QWidget();
    QVBoxLayout *viewAppointmentLayout = new QVBoxLayout(viewAppointmentTab);
    appointmentListWidget = new QListWidget(viewAppointmentTab); // 初始化列表框

    QPushButton *refreshButton = new QPushButton("刷新预约状态", viewAppointmentTab);
    viewAppointmentLayout->addWidget(appointmentListWidget);
    viewAppointmentLayout->addWidget(refreshButton);

    connect(refreshButton, &QPushButton::clicked, this, &PatientClient::onViewAppointments);

    tabWidget->addTab(viewAppointmentTab, "查看预约状态");

    // 设置主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(tabWidget);
    setLayout(mainLayout);

    // 初始化时加载预约状态
    onViewAppointments();
}

void PatientClient::onRequestAppointment()
{
    int doctorId = doctorComboBox->currentData().toInt();
    QDateTime appointmentDate = appointmentDateTimeEdit->dateTime();

    QSqlQuery query;
    query.prepare("INSERT INTO appointments (patient_id, doctor_id, appointment_date, status) VALUES (?, ?, ?, 'pending')");
    query.addBindValue(getPatientId(patientName));
    query.addBindValue(doctorId);
    query.addBindValue(appointmentDate);

    if (query.exec()) {
        QMessageBox::information(this, "预约成功", "您的预约请求已提交，请等待医生确认。");
    } else {
        QMessageBox::warning(this, "预约失败", "无法提交预约请求: " + query.lastError().text());
    }
}

void PatientClient::onViewAppointments()
{
    appointmentListWidget->clear();
    int patientId = getPatientId(patientName);

    QSqlQuery query;
    query.prepare("SELECT d.name, a.appointment_date, a.status FROM appointments a "
                  "JOIN doctors d ON a.doctor_id = d.doctor_id "
                  "WHERE a.patient_id = ?");
    query.addBindValue(patientId);

    if (query.exec()) {
        while (query.next()) {
            QString doctorName = query.value(0).toString();
            QString appointmentDate = query.value(1).toDateTime().toString("yyyy-MM-dd HH:mm");
            QString status = query.value(2).toString();
            appointmentListWidget->addItem(QString("医生: %1\n预约时间: %2\n状态: %3\n")
                                           .arg(doctorName, appointmentDate, status));
        }
    } else {
        QMessageBox::warning(this, "查询失败", "无法获取预约状态: " + query.lastError().text());
    }
}

// 根据患者姓名获取患者ID
int PatientClient::getPatientId(const QString &name)
{
    QSqlQuery query;
    query.prepare("SELECT patient_id FROM patients WHERE name = ?");
    query.addBindValue(name);
    if (query.exec() && query.next()) {
        return query.value(0).toInt();
    }
    return -1; // 如果找不到则返回-1
}

// 从 medical_history 表中获取对应的医生ID
int PatientClient::getCurrentDoctorId()
{
    int patientId = getPatientId(patientName); // 获取当前患者ID
    if (patientId == -1) {
        return -1; // 如果患者ID无效，则返回-1
    }

    QSqlQuery query;
    // 获取最新一条病历记录中的 doctor_id
    query.prepare("SELECT doctor_id FROM medical_history WHERE patient_id = ? ORDER BY visit_date DESC LIMIT 1");
    query.addBindValue(patientId);

    if (query.exec() && query.next()) {
        return query.value(0).toInt(); // 返回 doctor_id
    } else {
        qDebug() << "查询医生ID失败:" << query.lastError().text();
        return -1; // 如果查询失败或无记录，则返回-1
    }
}
